/*
 * DBeaver - Universal Database Manager
 * Copyright (C) 2010-2023 DBeaver Corp and others
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.cloudbeaver;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class H2QueryExecutor {
    private final String dbUrl;
    private final Properties dbProperties;

    public H2QueryExecutor(String dbUrl, Properties dbProperties) {
        this.dbUrl = dbUrl;
        this.dbProperties = dbProperties;
    }


    public void executeQuery(String query) throws SQLException, ClassNotFoundException {
        System.out.println("Execute query: " + query);

        try (
            var connection = DriverManager.getConnection(dbUrl, dbProperties);
            var statement = connection.createStatement()
        ) {
            statement.execute(query);
            var result = statement.getResultSet();
            if (result == null) {
                return;
            }
            var meta = result.getMetaData();
            while (result.next()) {
                for (var i = 1; i <= meta.getColumnCount(); i++) {
                    var className = meta.getColumnClassName(i);
                    var clazz = Class.forName(className);
                    System.out.print(result.getObject(i, clazz) + " ");
                }
                System.out.println();
            }
        }
    }

    public void execute11MigrationFix() throws SQLException, ClassNotFoundException {
        var queries = SqlConsts.fix11MigrationQueries.split(";");
        for (String query : queries) {
            executeQuery(query);
        }
    }
}
